import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2btrailer/b2btrailerselfpickupsubmitscreen.dart';
import 'package:opene/ui/b2btrailer/b2btrailermodel.dart';
import 'package:opene/ui/b2ctrailer/b2ctrailermodel.dart';
import 'package:opene/ui/fbapick/fbapickmodel.dart';
import 'package:toast/toast.dart';

class FBAPickCategoryScreen extends StatelessWidget {
  FBAPickInfo fbaPickInfo;

  FBAPickCategoryScreen({this.fbaPickInfo});

  @override
  Widget build(BuildContext context) {
    return FBAPickCategoryScreenPage(fbaPickInfo: fbaPickInfo);
  }
}

class FBAPickCategoryScreenPage extends StatefulWidget {
  FBAPickInfo fbaPickInfo;

  FBAPickCategoryScreenPage({this.fbaPickInfo});

  @override
  _FBAPickCategoryPageState createState() => _FBAPickCategoryPageState(fbaPickInfo: fbaPickInfo);
}

class _FBAPickCategoryPageState extends BaseState<FBAPickCategoryScreen> {
  FBAPickInfo fbaPickInfo;

  List<FBAPickLPN> data = new List();

  _FBAPickCategoryPageState({this.fbaPickInfo});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Pickup:Category";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        fbaPick(0);
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    "PickNo: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "Container: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "ContainerCode: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "Destination: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "Fba No: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "Job No: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
              Expanded(
                child: Column(
                  children: [
                    Text(
                      fbaPickInfo == null ? "" : Utils.getStringisEmpty(fbaPickInfo.pickNo),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      fbaPickInfo == null ? "" : Utils.getStringisEmpty(fbaPickInfo.container),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      fbaPickInfo == null ? "" : Utils.getStringisEmpty(fbaPickInfo.containerNo),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      fbaPickInfo == null ? "" : Utils.getStringisEmpty(fbaPickInfo.destination),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      fbaPickInfo == null ? "" : Utils.getStringisEmpty(fbaPickInfo.fbaNo),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      fbaPickInfo == null ? "" : Utils.getStringisEmpty(fbaPickInfo.jobNo),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 35),
            child: TextField(
              controller: textEditingController,
              textInputAction: TextInputAction.search,
              onSubmitted: (String text) {
                print('Searching for $text');
                if (Utils.isEmpty(text)) {
                  return;
                }
                fbaPickSubmit(text);
              },
              // autofocus: true,
              decoration: InputDecoration(
                suffixIcon: IconButton(
                  padding: EdgeInsets.all(2.0),
                  icon: Icon(
                    Icons.qr_code_scanner,
                    size: 28,
                    color: MyAppTheme.nearlyBlue,
                  ),
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                      return ScanCode();
                    })).then((text) {
                      if (text == null) {
                        return;
                      }
                      setState(() {
                        textEditingController.text = text;
                      });
                      print(text); //拿到扫描结果
                      fbaPickSubmit(text);
                    });
                  },
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: MyAppTheme.nearlyBlue,
                  ),
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点之外的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点时的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                hintText: "scan inbound lpn barcode",
                filled: true,
                fillColor: MyAppTheme.white,
                //隐藏下划线
                //border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.grey),
                contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
              ),
              onChanged: (text) {
                code = text;
              },
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Expanded(
                flex: 1, //设置权重
                child: GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    if (type == 1) {
                      return;
                    }

                    setState(() {
                      type = 1;
                      fbaPick(0);
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'LPN List',
                      style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    if (type == 2) {
                      return;
                    }
                    fbaPick(1);
                  },
                  child: Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Lpn Out',
                      style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Expanded(child: setListView())
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        FBAPickLPN trailerOBLPN = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Text(
                      "${Utils.getStringisEmpty(trailerOBLPN.lpn)} (${Utils.getStringisEmpty(trailerOBLPN.containerNo)})",
                      style: Utils.isEmpty(trailerOBLPN.dataSource)
                          ? MyAppTheme.testred12
                          : trailerOBLPN.dataSource == "wms"
                              ? MyAppTheme.test12
                              : MyAppTheme.testred12,
                    )),
                Visibility(
                  visible: type == 2 ? true : false,
                  child: GestureDetector(
                    onTap: () {
                      fbaPickCancel(Utils.getStringisEmpty(trailerOBLPN.lpn));
                    },
                    child: Icon(
                      Icons.delete,
                      size: 20,
                      color: MyAppTheme.grey,
                    ),
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void fbaPick(int isPick) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, "${Constants.fbaPick}/${isPick}/lpns/${fbaPickInfo.pickNo}");

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => FBAPickLPN.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void fbaPickCancel(String lpn) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, "${Constants.fbaPickCancel}/${fbaPickInfo.pickNo}/cancel/${lpn}",method: BaseMethod.put);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        fbaPick(type - 1);
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void fbaPickSubmit(String lpn) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    FBASubmit fbaSubmit = new FBASubmit();
    fbaSubmit.lpn = lpn;
    fbaSubmit.pickNo = fbaPickInfo.pickNo;
    String json = jsonEncode(fbaSubmit);
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaPickSubmit, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      fbaPick(type - 1);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {}

  @override
  void setNext() {}

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}

class CustomDialog extends StatefulWidget {
  String lpn;
  String trailer;

  CustomDialog({this.lpn, this.trailer});

  @override
  _CustomDialogState createState() => _CustomDialogState(lpn: lpn, trailer: trailer);
}

class _CustomDialogState extends State<CustomDialog> {
  String lpn;
  String trailer;

  _CustomDialogState({this.lpn, this.trailer});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Remove ${lpn} form ${trailer}", style: MyAppTheme.textred14),
            SizedBox(height: 16.0),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(false);
                      },
                    )),
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Confirm',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(true);
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
